package com.win.oauth.controller;


import com.fyl.core.response.RS;
import com.win.oauth.utils.SseEmitterUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@CrossOrigin("*")
@RestController
@RequestMapping("/sse")
public class SSEController {

    /**
     * sse 订阅消息
     */
    @GetMapping(path = "sub/{username}", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public SseEmitter sub(@PathVariable String username) throws IOException {
        return SseEmitterUtils.connect(username);
    }

    /**
     * sse 发布消息
     */
    @GetMapping(path = "push")
    public RS<Void> push(String username, String content) throws IOException {
        SseEmitterUtils.sendMessage(username, content);
        return RS.genSuccess();
    }

    @GetMapping(path = "breakConnect")
    public RS<Void> breakConnect(String username, HttpServletRequest request, HttpServletResponse response) {
        request.startAsync();
        SseEmitterUtils.removeUser(username);
        return RS.genSuccess();
    }
}

